package com.wakala.employment.fragment.profile;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.gzuliyujiang.wheelpicker.AddressPicker;
import com.github.gzuliyujiang.wheelpicker.annotation.AddressMode;
import com.github.gzuliyujiang.wheelpicker.contract.OnAddressPickedListener;
import com.github.gzuliyujiang.wheelpicker.contract.OnLinkageSelectedListener;
import com.github.gzuliyujiang.wheelpicker.contract.OnNumberSelectedListener;
import com.github.gzuliyujiang.wheelpicker.entity.CityEntity;
import com.github.gzuliyujiang.wheelpicker.entity.CountyEntity;
import com.github.gzuliyujiang.wheelpicker.entity.ProvinceEntity;
import com.github.gzuliyujiang.wheelpicker.widget.NumberWheelLayout;
import com.hjq.toast.Toaster;
import com.kongzue.dialogx.dialogs.FullScreenDialog;
import com.kongzue.dialogx.dialogs.InputDialog;
import com.kongzue.dialogx.interfaces.OnBindView;
import com.kongzue.dialogx.interfaces.OnInputDialogButtonClickListener;
import com.leaf.library.StatusBarUtil;
import com.wakala.employment.R;
import com.wakala.employment.adapter.base.FlowTagAdapter;
import com.wakala.employment.core.BaseFragment;
import com.wakala.employment.databinding.FragmentBasicsInfoBinding;
import com.wakala.employment.databinding.FragmentProfileBinding;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.enums.CoreAnim;
import com.xuexiang.xui.XUI;
import com.xuexiang.xui.utils.ResUtils;
import com.xuexiang.xui.utils.Utils;
import com.xuexiang.xui.utils.XToastUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.flowlayout.FlowTagLayout;
import com.xuexiang.xutil.XUtil;
import com.xuexiang.xutil.common.RegexUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link BasicsInfoFragment#} factory method to
 * create an instance of this fragment.
 */
@Page(anim = CoreAnim.none)
public class BasicsInfoFragment extends BaseFragment<FragmentBasicsInfoBinding> implements View.OnClickListener {


     private TextView btnCancel,btnSubmit,tvSalaryUnitName;
     private FlowTagLayout mSingleFlowTagLayout;

     private LinearLayout llSalaryRange;

     private NumberWheelLayout numSalaryStart,numSalaryEnd;

     private String unitCode="";
     private String unitName="";

    /**
     * 薪资范围 起
     */
    private Integer rangeStart=0;
    /**
     * 薪资范围 至
     */
     private Integer rangeEnd = 0;

     private Map<String,String> unitValueMap = new HashMap<>();
     private Map<Integer,String> unitIndexeMap = new HashMap<>();

     private Boolean hasSelectSalaryRang = false;

    @NonNull
    @Override
    protected FragmentBasicsInfoBinding viewBindingInflate(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, boolean attachToRoot) {
        return FragmentBasicsInfoBinding.inflate(inflater, container, attachToRoot);
    }

    /**
     * @return 返回为 null意为不需要导航栏
     */
    @Override
    protected TitleBar initTitle() {
        TitleBar titleBar = super.initTitle();
        titleBar.setTitle("基础资料");
        titleBar.setTitleColor(R.color.black);
        titleBar.setLeftTextColor(R.color.black);
        titleBar.setLeftImageDrawable(getResources().getDrawable(R.drawable.icon_arrow_back));
        titleBar.setBackgroundResource(R.color.white);//设置标题栏背景颜色
        StatusBarUtil.setDarkMode(getActivity());
        //设置状态栏背景颜色，如果设置为 Color.TRANSPARENT 将会隐藏状态栏
        getActivity().getWindow().setStatusBarColor(getResources().getColor(R.color.white));
        return titleBar;
    }

    @Override
    protected void initListeners() {
        binding.stvModifyKind.setOnClickListener(this);
        binding.stvJobAddress.setOnClickListener(this);
        binding.stvJobSalary.setOnClickListener(this);
        binding.stvPhoneNumber.setOnClickListener(this);
    }

    @Override
    protected void initArgs() {
        super.initArgs();
        unitValueMap.put("R","日");
        unitValueMap.put("Y","月");
        unitValueMap.put("J","件");
        unitValueMap.put("M","面议");
        //
        unitIndexeMap.put(0,"R");
        unitIndexeMap.put(1,"Y");
        unitIndexeMap.put(2,"J");
        unitIndexeMap.put(3,"M");
    }

    @Override
    protected void initViews() {

    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if(id == R.id.stv_modify_kind){
            openNewPage(FindJobInfoFragment.class);
        }else if (id == R.id.stv_job_address){//选择工作地
            showProvinceCitySelect();
        }else if(id == R.id.stv_job_salary){//选择薪水
            showSalarySelect();
        }else if(id ==R.id.stv_phone_number){
            showBindPhoneNumber();
        }
    }

    private void showBindPhoneNumber(){
        new InputDialog("系统提示", "请输入正确的手机号码", "确定", "取消", "")
                .setCancelable(false)
                .setOkButton(new OnInputDialogButtonClickListener<InputDialog>() {
                    @Override
                    public boolean onClick(InputDialog baseDialog, View v, String inputStr) {
                        if(RegexUtils.isMobileExact(inputStr)){
                            binding.stvPhoneNumber.setCenterString(inputStr);
                            binding.stvPhoneNumber.setCenterTextColor(getResources().getColor(R.color.black));
                            baseDialog.dismiss();
                        }else{
                            Toaster.show("输入的手机号码不正确");
                        }
                        return true;
                    }
                })
                .show();
    }

    private void initSingleFlowTagLayout() {
        FlowTagAdapter tagAdapter = new FlowTagAdapter(getContext());
        mSingleFlowTagLayout.setAdapter(tagAdapter);
        mSingleFlowTagLayout.setTagCheckedMode(FlowTagLayout.FLOW_TAG_CHECKED_SINGLE);
        mSingleFlowTagLayout.setOnTagSelectListener((parent, position, selectedList) -> DoOnTagSelect(parent, position, selectedList));
        tagAdapter.addTags(ResUtils.getStringArray(getContext(), R.array.tags_values));
        tagAdapter.setSelectedPositions(0);

    }
    private String DoOnTagSelect(FlowTagLayout parent,int position, List<Integer> selectedList) {
        StringBuilder sb = new StringBuilder("选中的内容：\n");
        for (int index : selectedList) {
            sb.append(parent.getAdapter().getItem(index));
            sb.append(";");
        }
        if(3==position){
            llSalaryRange.setVisibility(View.GONE);
        }else {
            llSalaryRange.setVisibility(View.VISIBLE);
        }
        initNumSalaryPicker(position);
        getSalaryUnitStr(position);
        return sb.toString();
    }

    /**
     * 薪水范围选贼器 数据选中事件绑定
     */
    private void bindEventSalaryPicker(){
        numSalaryStart.setOnNumberSelectedListener(new OnNumberSelectedListener() {
            @Override
            public void onNumberSelected(int position, Number item) {
                rangeStart = item.intValue();
                //设置薪水返回已经选择过
                hasSelectSalaryRang = true;
            }
        });
        numSalaryEnd.setOnNumberSelectedListener(new OnNumberSelectedListener() {
            @Override
            public void onNumberSelected(int position, Number item) {
                rangeEnd = item.intValue();
            }
        });
    }

    private void initNumSalaryPicker(Integer jieSuanFS){
        if(null==jieSuanFS){
            jieSuanFS=0;
        }
        if(jieSuanFS==0){
            //日结
            numSalaryStart.setRange(100,2000,100);
            numSalaryEnd.setRange(200,2100,100);
            //初始化选择器的选值
            rangeStart = 100;
            rangeEnd = 200;
        }else if(jieSuanFS==1){
            //月结
            numSalaryStart.setRange(1000,290000,1000);
            numSalaryEnd.setRange(2000,300000,1000);
            //初始化选择器的选值
            rangeStart = 1000;
            rangeEnd = 2000;
        }else if(jieSuanFS==2){
            //计量
            numSalaryStart.setRange(1,490,10);
            numSalaryEnd.setRange(10,500,10);
            //初始化选择器的选值
            rangeStart = 1;
            rangeEnd = 10;
        }
    }

    private String getSalaryUnitStr(Integer unitIndex){
            String pre="单位：元/";
            if(3==unitIndex){
                pre="";
            }
            unitCode = unitIndexeMap.get(unitIndex);
            unitName=unitValueMap.get(unitIndexeMap.get(unitIndex));
            tvSalaryUnitName.setText(pre+unitName);
            return pre+unitName;
    }

    private void showSalarySelect(){
        /**
         * 采用异步加载布局防止卡顿测试
         */

        OnBindView<FullScreenDialog> onBindView;
        onBindView = new OnBindView<FullScreenDialog>(R.layout.layout_dialog_salary, false) {
            @Override
            public void onBind(FullScreenDialog dialog, View v) {
                btnCancel = v.findViewById(R.id.btn_cancel);
                btnSubmit = v.findViewById(R.id.btn_submit);
                tvSalaryUnitName = v.findViewById(R.id.tv_salary_mode_name);
                mSingleFlowTagLayout = v.findViewById(R.id.flowlayout_single_select);
                llSalaryRange = v.findViewById(R.id.ll_salary_range);
                initSingleFlowTagLayout();
                numSalaryStart = v.findViewById(R.id.num_salary_start);
                numSalaryEnd = v.findViewById(R.id.num_salary_end);
                initNumSalaryPicker(0);
                bindEventSalaryPicker();
                getSalaryUnitStr(0);
                /*boxUserName = v.findViewById(R.id.box_userName);
                editUserName = v.findViewById(R.id.edit_userName);
                boxPassword = v.findViewById(R.id.box_password);
                editPassword = v.findViewById(R.id.edit_password);
                btnLicense = v.findViewById(R.id.btn_license);*/

                initFullScreenLoginDemo(dialog);
            }
        };
        FullScreenDialog.show(onBindView);
    }
    private void initFullScreenLoginDemo(final FullScreenDialog fullScreenDialog) {
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fullScreenDialog.dismiss();
            }
        });

        btnCancel.setText("取消");
        btnSubmit.setText("确定");

       /* btnLicense.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PopTip.show("点击用户服务条款");
            }
        });*/

        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(rangeStart>=rangeEnd && !unitCode.equals("M")){
                    Toaster.show("薪资范围选择错误，起始薪资大于结束薪资");
                }else {
                    fullScreenDialog.dismiss();
                    //Toaster.show(rangeStart+"-"+rangeEnd+"元/"+unitName);
                    if(unitCode.equals("M")){
                        binding.stvJobSalary.setCenterString(unitName);
                    }else {
                        binding.stvJobSalary.setCenterString(rangeStart+"-"+rangeEnd+"元/"+unitName);
                    }
                    binding.stvJobSalary.setCenterTextColor(getResources().getColor(R.color.black));

                }

                /*if (isNull(editUserName.getText().toString().trim())) {
                    hideIME(null);
                    TipDialog.show("请输入账号", TipDialog.TYPE.WARNING);
                    return;
                }

                boxUserName.animate().x(-getDisplayWidth()).setDuration(300);
                boxPassword.setX(getDisplayWidth());
                boxPassword.setVisibility(View.VISIBLE);
                boxPassword.animate().x(0).setDuration(300);

                editPassword.setFocusable(true);
                editPassword.requestFocus();

                btnCancel.setText("上一步");
                btnCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        boxUserName.animate().x(0).setDuration(300);
                        boxPassword.animate().x(getDisplayWidth()).setDuration(300);

                        editUserName.setFocusable(true);
                        editUserName.requestFocus();

                        initFullScreenLoginDemo(fullScreenDialog);
                    }
                });

                btnSubmit.setText("登录");*/
                /*btnSubmit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        hideIME(null);
                        if (isNull(editPassword.getText().toString().trim())) {
                            TipDialog.show("请输入密码", TipDialog.TYPE.WARNING);
                            return;
                        }
                        WaitDialog.show("登录中...");
                        runOnMainDelayed(new Runnable() {
                            @Override
                            public void run() {
                                TipDialog.show("登录成功", TipDialog.TYPE.SUCCESS).setDialogLifecycleCallback(new DialogLifecycleCallback<WaitDialog>() {
                                    @Override
                                    public void onDismiss(WaitDialog dialog) {
                                        fullScreenDialog.dismiss();
                                    }
                                });
                            }
                        }, 2000);
                    }
                });*/
            }
        });
    }
    private void showProvinceCitySelect(){
        AddressPicker picker = new AddressPicker(getActivity());
        picker.setTitle("省市选择");
        picker.setAddressMode(AddressMode.PROVINCE_CITY);
        picker.setDefaultValue("520000", "520100", "");
        picker.setOnAddressPickedListener(new OnAddressPickedListener() {
            @Override
            public void onAddressPicked(ProvinceEntity province, CityEntity city, CountyEntity county) {

            }
        });
        picker.getWheelLayout().setOnLinkageSelectedListener(new OnLinkageSelectedListener() {
            @Override
            public void onLinkageSelected(Object first, Object second, Object third) {
                String provinceCity = String.format("%s%s%s",
                        picker.getFirstWheelView().formatItem(first),
                        picker.getSecondWheelView().formatItem(second),
                        picker.getThirdWheelView().formatItem(third));
                picker.getTitleView().setText(provinceCity);
                binding.stvJobAddress.setCenterString(provinceCity);
                binding.stvJobAddress.setCenterTextColor(getResources().getColor(R.color.black));
            }
        });
        picker.show();
    }
}